const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
  // 该参数从 wx-server-sdk 1.7.0 开始支持，默认为 true，指定 false 后可使得 doc.get 在找不到记录时不抛出异常
  throwOnNotFound: false,
})
const _ = db.command

exports.main = async (event) => {
  const wxContext = cloud.getWXContext()
  console.log("【event】",event)
  var arr = event.date.split('/')
  var time = 0
  switch (event.time) {
    case '0':
      time = 8
      break
    case '1':
      time = 10
      break
    case '2':
      time = 14
      break
    case '3':
      time = 16
      break
    case '4':
      time = 18
      break
    case '5':
      time = 20
      break
  }
  console.log("time",time-8)
  var date=new Date(arr[0],arr[1]-1,arr[2],time-8)
  console.log(date)
  try {
    const result = await db.runTransaction(async transaction => {
      //锁定这条对象
      await transaction.collection('RoomList').doc('currentDepartment').update({
        data: {
          locked: true
        }
      })
      //获取数据
      const RoomList = await transaction.collection('RoomList').doc('currentDepartment').get()
      const UserBooking = await transaction.collection('User').doc(wxContext.OPENID).get()

      if (RoomList && UserBooking) {
        var list = RoomList.data.RoomList
        if (list[event.id].book[event.date]) {
          console.log("该日期已存在")
        } else {
          console.log("该日期不存在，创建日期")
          list[event.id].book[event.date] = [1, 1, 1, 1, 1, 1]
        }
        if (list[event.id].book[event.date][event.time] == 1) {
          list[event.id].book[event.date][event.time] = 3
          const updateBook = await transaction.collection('RoomList').doc('currentDepartment').update({
            data: {
              RoomList: list
            }
          })
          var bookObj = {}
          bookObj.roomId = event.id
          bookObj.status = 0
          bookObj.time = date
          bookObj.select=event.time
          bookObj.date=event.date
          await transaction.collection('User').doc(wxContext.OPENID).update({
            data: {
              booking: _.push(bookObj)
            }
          }).then(res => {
            console.log("update User", res)
          })
          await transaction.collection('Booking').add({
            data: {
              roomId: event.id,
              status: 0,
              name: event.name,
              time: bookObj.time,
              tel: event.tel,
              person: event.person,
              note: event.note
            }
          }).then(res => {
            console.log(res._id)
          })
          await transaction.collection('RoomList').doc('currentDepartment').update({
            data: {
              locked: false
            }
          })
        } else {
          await transaction.rollback("该房间已被预定")
        }

        // 会作为 runTransaction resolve 的结果返回
        return {
          success: true,
        }
      } else {
        // 会作为 runTransaction reject 的结果出去
        await transaction.rollback("读取失败")
      }
    })

    return {
      success: true,
    }
  } catch (e) {
    console.error(`transaction error`, e)

    return {
      success: false,
      error: e
    }
  }
}